package work.chenxr.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author Chenxr
 * @Date 2023/10/18
 * @Description RabbitMq配置
 */
@Configuration
public class RabbiMqConfig {
    /**
     * 队列 - 接收延迟投递的队列
     *
     * @param chenxrQueue 队列名称
     */
    @Bean
    public Queue chenxrDelayQueue(@Value("${app.rabbitmq.delay.chenxr.queue}") String chenxrQueue) {
        return QueueBuilder.durable(chenxrQueue).build();
    }

    /**
     * 交换机-延迟交换机 - 消息延迟一定时间之后再投递到绑定的队列
     *
     * @param chenxrExchange 延迟交换机
     */
    @Bean
    public Exchange chenxrDelayExchange(@Value("${app.rabbitmq.delay.chenxr.exchange}") String chenxrExchange) {
        Map<String, Object> args = new HashMap<>(1);
        args.put("x-delayed-type", "topic");
        return new CustomExchange(chenxrExchange, "x-delayed-message", true, false, args);
    }

    /**
     * 队列-交换机 绑定
     *
     * @param chenxrDelayQueue    队列
     * @param chenxrDelayExchange 交换机
     */
    @Bean
    public Binding chenxrBinding(Queue chenxrDelayQueue, Exchange chenxrDelayExchange) {
        return BindingBuilder
                .bind(chenxrDelayQueue)
                .to(chenxrDelayExchange)
                .with("delay.chenxr.*")
                .noargs();
    }
}
